package top.hidoctor.auscultation.feature.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.tang.util.AppUtil;
import com.tang.util.BigDecimalUtil;
import com.tang.util.DensityUtil;
import com.tang.util.GsonUtil;
import com.tang.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.JsonBean;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.event.XinyinEvent;
import top.hidoctor.auscultation.utils.BigorLittle;
import top.hidoctor.auscultation.utils.BlueToothDataUtils;
import top.hidoctor.auscultation.utils.GetJsonDataUtil;
import top.hidoctor.auscultation.utils.LabelUtils;
import top.hidoctor.auscultation.utils.MyInternalStorage;
import top.hidoctor.auscultation.view.LocEcgView;
import top.hidoctor.auscultation.widget.Player;
import top.hidoctor.auscultation.widget.mark.MyHScrollView;

public class XinyinDetailActivity extends BaseActivity {

    private TextView tv_file_name, tv_shengao, tv_tizhong, tv_tiwei, tv_chengdu, tv_zhengjin, tv_shoushu, tv_changsuo, tv_address, tv_time, tv_delete;
    private SeekBar seekBar;
    private ImageView ivBofang;
    private LinearLayout llEcg;
    private MyHScrollView horizontalScroll;
    private String pcmInfo;
    private ArrayList<Float> data = new ArrayList<>();
    private LinearLayout llEcgContent;
    private PatientLocalInfo info;
    private int playStatus = 0;// 0 零状态  1 开始 2 暂停
    private Player player;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_xinyin_detail);
        info = (PatientLocalInfo) getIntent().getSerializableExtra("info");
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (info != null && !TextUtils.isEmpty(info.getPcmFileName())) {
            showLoading();
            try {
                pcmInfo = new MyInternalStorage(this).get(info.getPcmFileName());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getLocation(pcmInfo);
                    }
                }).start();
            } catch (IOException e) {
                e.printStackTrace();
                hideLoading();
            }
        }
    }

    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        final TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tvTitle.setText("详细信息");
        tv_file_name = findViewById(R.id.tv_file_name);
        tv_shengao = findViewById(R.id.tv_shengao);
        tv_tizhong = findViewById(R.id.tv_tizhong);
        tv_tiwei = findViewById(R.id.tv_tiwei);
        tv_chengdu = findViewById(R.id.tv_chengdu);
        tv_zhengjin = findViewById(R.id.tv_zhengjin);
        tv_shoushu = findViewById(R.id.tv_shoushu);
        tv_changsuo = findViewById(R.id.tv_changsuo);
        tv_address = findViewById(R.id.tv_address);
        tv_time = findViewById(R.id.tv_time);
        seekBar = findViewById(R.id.seekBar);
        ivBofang = findViewById(R.id.iv_bofang);
        tv_delete = findViewById(R.id.tv_delete);
        llEcg = findViewById(R.id.ll_ecg);
        llEcgContent = findViewById(R.id.ll_ecg_content);
        horizontalScroll = findViewById(R.id.horizontal_scrolls);

        //设置网格背景
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        Bitmap bitmap = drawBackground(20, DensityUtil.dip2px(this, 140), displayMetrics.widthPixels - DensityUtil.dip2px(this, 60));
        horizontalScroll.setBackground(new BitmapDrawable(bitmap));

        tv_time.setText(AppUtil.stringForTime2(info.getDuration()) + "/00:00");
        player = new Player(seekBar);
        ivBofang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playStatus == 0) { // 播放状态
                    playStatus = 1;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            player.playUrl(mContext.getFilesDir().getAbsolutePath() + "/" + info.getFileName());
                        }
                    }).start();
                    ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                } else if (playStatus == 1) {// 暂停状态
                    playStatus = 2;
                    if (player != null) {
                        player.pause();
                    }
                    ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                } else if (playStatus == 2) { //继续播放
                    playStatus = 1;
                    if (player != null) {
                        player.play();
                    }
                    ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                }
            }
        });

        player.setOnplayerListener(new Player.OnplayerListener() {
            @Override
            public void onCompletion() {
                //播放完成
                playStatus = 0;
                ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                tv_time.setText(AppUtil.stringForTime2(info.getDuration()) + "/00:00");
            }
        });


        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                final int currentPosition = seekBar.getProgress();
                tv_time.setText(AppUtil.stringForTime2(info.getDuration()) + "/" + AppUtil.stringForTime2(currentPosition));
                Log.e("TAG", " onProgressChanged:  " + seekBar.getProgress());
                Integer duration = info.getDuration();
//                真实滑动长度
                int width = 0;
                if (horizontalScroll.getWidth() < llEcgContent.getWidth()) {
                    width = llEcgContent.getWidth() - horizontalScroll.getWidth();
                } else {
                    width = horizontalScroll.getWidth();
                }
                horizontalScroll.smoothScrollTo((int) Math.round(BigDecimalUtil.div(currentPosition, duration) * width), 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                player.seekTo(seekBar.getProgress());
            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(XinyinDetailActivity.this);
                builder.setMessage("确定删除该样本吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                MyInternalStorage myInternalStorage = new MyInternalStorage(XinyinDetailActivity.this);
                                //删除wav文件
                                boolean delete = myInternalStorage.delete(info.getFileName());
                                myInternalStorage.delete(info.getPcmFileName());

                                //删除数组
                                String content = (String) SPUtil.get(XinyinDetailActivity.this, Constant.LOCAL_INFO, "");
                                Log.e("TAG", "initEvent: " + content);
                                if (!TextUtils.isEmpty(content)) {
                                    List<PatientLocalInfo> data = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
                                    });
                                    int removePos = -1;
                                    for (int i = 0; i < data.size(); i++) {
                                        if (data.get(i).getFileName().equals(info.getFileName())) {
                                            removePos = i;
                                            break;
                                        }
                                    }
                                    if (removePos != -1) {
                                        data.remove(removePos);
                                    }
                                    SPUtil.put(XinyinDetailActivity.this, Constant.LOCAL_INFO, GsonUtil.toJsonStr(data));
                                }

                                if (delete) {
                                    showToast("删除成功");
                                    EventBus.getDefault().post(new XinyinEvent());
                                    finish();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        });
    }


    /**
     * 设置背景
     *
     * @param cellSize
     * @param height
     * @param widht
     * @return
     */
    public Bitmap drawBackground(int cellSize, int height, int widht) {
        Bitmap bitmap = Bitmap.createBitmap(widht, height, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(bitmap);
        Paint background = new Paint();
        background.setColor(Color.WHITE);
        cv.drawRect(0, 0, widht, height, background);
        background.setAntiAlias(true);
        background.setColor(Color.parseColor("#cccccc"));
        for (int i = 0; i < widht / cellSize + 1; i++) {
            cv.drawLine(cellSize * i, 0, cellSize * i, height, background);
        }
        for (int i = 0; i < height / cellSize + 1; i++) {
            cv.drawLine(0, cellSize * i, widht, cellSize * i, background);
        }
        return bitmap;
    }


    private void initEvent() {
        if (info != null) {
            tv_file_name.setText(info.getName());
            tv_shengao.setText(info.getShengao());
            tv_tizhong.setText(info.getTizhong());
            tv_tiwei.setText(info.getTiwei());
            tv_chengdu.setText(info.getPeihe());
            tv_changsuo.setText(info.getChangsuo());
            tv_address.setText(info.getAddress());
            tv_zhengjin.setText(info.getZhengjing().equals("1") ? "是" : "否");
            tv_shoushu.setText(info.getShoushu().equals("1") ? "是" : "否");
            seekBar.setMax(info.getDuration());
        }
    }


    private void getLocation(String pcmInfo) {

//        String JsonData = new GetJsonDataUtil().getJson(this, "info2.json");//获取assets目录下的json文件数据

//        try {
//            pcmInfo = String.valueOf(new JSONObject(JsonData).get("data"));
            for (int i = 0; i < pcmInfo.length() - 1; i += 4) {
//                if (i + 4 < pcmInfo.length()) {
                    Float point = BlueToothDataUtils.getComplement(pcmInfo.substring(i, i + 4));
                    this.data.add(point);
//                }
            }
            final List<List<Float>> list = LabelUtils.groupList(this.data);
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            int width = displayMetrics.widthPixels - DensityUtil.dip2px(this, 60);
            final float gap_x = (float) BigDecimalUtil.div(width, 10000);
            this.runOnUiThread(new Runnable() {
                public void run() {
                    for (int i = 0; i < list.size(); i++) {
                        final LocEcgView ecgView = new LocEcgView(XinyinDetailActivity.this);
                        ecgView.setDate(list.get(i), gap_x);
                        llEcgContent.addView(ecgView);
                    }
                }
            });
            hideLoading();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }
}
